import axios from "axios";
import { useUserStore } from '@/stores/user'
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { getNewToken } from "@/api/user";


const baseURL = "http://localhost:9999";
export function reqeust(config) {
  const router = useRouter()
  const instance = axios.create({
    baseURL,
    timeout: 5000,
  });
  // 请求拦截
  instance.interceptors.request.use(
    // 封装token
    (config) => {
      const userStore = useUserStore()
      if (userStore.accessToken) {
        config.headers.Authorization = `${userStore.accessToken}`;
      }
      return config;
    },
    (err) => {
      return Promise.reject(err);
    }
  );
  // 响应拦截器
  instance.interceptors.response.use(
    async (res) => {
      if (res.data.code == 0) {
        return res.data;
      }
      const originalRequest = res.config
      // 业务请求异常
      if (res.data.code == 1008 && !originalRequest._retry && originalRequest.url !== '/admin/refresh') {
        originalRequest._retry = true
        ElMessage.error('TOKEN 已过期！正在刷新 TOKEN...');
        const userStore = useUserStore()
        // 尝试刷新token
        const refreshToken = userStore.refreshToken
        const response = await getNewToken({ refreshToken })
        userStore.setAccessToken(response.data.accessToken)
        // 重新发送原始请求
        originalRequest.headers.Authorization = `${userStore.accessToken}`
        return instance(originalRequest)
      } else {
        // ElMessage.error(res.data.msg ?? '服务异常');
        ElMessage.error('00服务异常');
        return Promise.reject(res.data)
      }
    },
    (err) => {
      return Promise.reject(err);
    }
  );
  // 返回axios实例
  return instance(config);
}

export function get(url, params) {
  return reqeust({
    url,
    method: "get",
    params,
  });
}
export function post(url, data) {
  return reqeust({
    url,
    method: "post",
    data: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json'
    }
  });
}
export function del(url, params) {
  return reqeust({
    url,
    method: "delete",
    params,
  });
}


export { baseURL };